<template>
  <main class="main">
    <el-alert
      style="position: fixed; top: 0; z-index: 3"
      :title="`答题即将在 ${END_ANSWER_TIME} 结束`"
      type="success"
      :closable="false"
    >
    </el-alert>
    <header class="header"><div>上海宋庆龄故居 · FDU20CS2</div></header>
    <transition name="slide">
      <div class="action-bar" v-if="show">
        <el-button
          class="submit-button"
          @click="
            submitAnswer(
              question.type === 0
                ? currentRadioAnswer
                : question.type === 1
                ? currentCheckboxAnswer.join(',')
                : currentTextAnswer,
            )
          "
          >{{
            this.currentQuestion === this.questionCount
              ? '提交并结束答题'
              : '提交'
          }}</el-button
        >
      </div>
    </transition>
    <!-- 题目 -->
    <transition name="slide">
      <div v-if="show">
        <div class="question">{{ question.title }}</div>
        <!-- 单选 -->
        <div v-if="question.type === 0" style="text-align: center">
          <el-radio-group v-model="currentRadioAnswer" size="mini">
            <transition
              v-for="(item, index) in question.options"
              :key="question.id + index"
              appear
              name="slide"
            >
              <el-radio
                style="display: block; margin: 20px 0; text-align: left"
                :label="LABELLIST[index]"
                border
                >{{ item }}</el-radio
              >
            </transition>
          </el-radio-group>
        </div>
        <!-- 多选 -->
        <div v-if="question.type === 1" style="text-align: center">
          <el-checkbox-group v-model="currentCheckboxAnswer" size="mini">
            <transition
              v-for="(item, index) in question.options"
              :key="question.id + index"
              appear
              name="slide"
            >
              <el-checkbox
                style="display: block; margin: 20px 0; text-align: left"
                :label="LABELLIST[index]"
                border
              >
                {{ item }}
              </el-checkbox>
            </transition>
          </el-checkbox-group>
        </div>
        <!-- 填空 -->
        <div v-if="question.type === 2" style="text-align: center">
          <transition appear name="slide">
            <el-input
              style="text-align: left"
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
              v-model="currentTextAnswer"
            >
            </el-input>
          </transition>
        </div>
      </div>
    </transition>
    <StatusBar
      class="bottom-bar"
      :count="questionCount"
      :current="currentQuestion"
      :setQuestion="moveQuestion.bind(this)"
    />
    <ResultPage v-if="isEnd" :result="true" :score="totalScore" />
  </main>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import CountdownTimer from '@/components/CountdownTimer';
import Option from '@/components/Option';
import ResultPage from '@/components/ResultPage';
import { GET_USER_INFO } from '@/store/mutation-types';
import StatusBar from '@/components/StatusBar';
import { getQuestion, personalRank, saveAnswer } from '@/api';

export default {
  name: 'Quiz',
  data() {
    return {
      input: '',
      show: false,
      question: {
        type: 0,
        title: '',
        options: [],
        id: '',
      },
      currentRadioAnswer: undefined,
      currentCheckboxAnswer: [],
      currentTextAnswer: undefined,
      questionList: {},
      questionCount: 0, // 总题数
      currentQuestion: 1, // 当前第几题
      isEnd: false, // 是否结束（全部答对或答错一题）
      // optionsInfo: [],
      // costTime: [], // 花费的时间，第一位开始时间，第二位结束时间
      totalScore: 0, // 总分
      LABELLIST: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
      ],
    };
  },
  methods: {
    resetData() {
      this.show = false;
      this.isRight = false;
      this.restTime = 10;
      this.input = '';
    },
    showQuestion() {
      // 获取题目
      getQuestion(this.token).then((response) => {
        if (response.data.code === 500) {
          this.$message({ type: 'error', message: '无权限访问' });
        } else {
          this.questionCount = response.data.page.totalCount;
          this.questionList = response.data.page.list;
          this.setQuestion(0);
        }
      });
    },
    submitAnswer(answer) {
      saveAnswer(
        {
          userId: this.userId,
          examAnswer: answer,
          examId: this.question.id,
        },
        this.token,
      ).then((res) => {
        if (res.data.code === 0) {
          this.currentRadioAnswer = undefined;
          this.currentCheckboxAnswer = [];
          this.currentTextAnswer = undefined;
          if (this.currentQuestion === this.questionCount) {
            setTimeout(() => {
              this.showResult();
            }, 200);
          } else {
            this.moveQuestion(this.currentQuestion);
          }
        } else {
          this.$message({ type: 'error', message: res.data.msg });
        }
      });
    },
    moveQuestion(questionIdx) {
      // 播放动画后继续下一题
      this.resetData();
      setTimeout(() => {
        this.setQuestion(questionIdx);
        this.currentQuestion = questionIdx + 1;
      }, 500);
    },
    setQuestion(questionIdx) {
      this.show = true;
      const current = this.questionList[questionIdx];
      if (typeof current.examOptions === 'string') {
        current.examOptions = current.examOptions.split('\n');
      }
      this.question.id = current.examId;
      this.question.type = current.examType;
      this.question.title = current.examTitle;
      if (current.examOptions != null && current.examOptions.length > 0) {
        this.question.options = current.examOptions;
      }
    },
    showResult() {
      // 展示答题完成结果
      personalRank().then((res) => {
        const rankList = res.data.rank;
        this.totalScore = rankList.find(
          ({ userId }) => userId === this.userId,
        ).score;
        this.isEnd = true;
      });
    },
    ...mapMutations({
      getUserInfo: GET_USER_INFO,
    }),
  },
  created() {
    this.resetData();
  },
  mounted() {
    this.getUserInfo();
    this.$nextTick(() => {
      this.showQuestion();
    });
  },
  beforeDestroy() {
    clearInterval(this.countdownInterval);
  },
  watch: {},
  computed: {
    ...mapState(['userId', 'token', 'userId', 'END_ANSWER_TIME']),
  },
  components: {
    CountdownTimer,
    Option,
    ResultPage,
    StatusBar,
  },
};
</script>

<style lang="scss" scoped src="./style.scss"></style>
